package org.cypress.rtpack.common.exception;

import org.cypress.rtpack.common.aspect.WebControllerLogAop;
import org.cypress.rtpack.common.core.Result;
import org.cypress.rtpack.common.utils.I18nUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionAdvice {
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionAdvice.class);
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Result handleException(Exception e) {
		// 预料之外的错误
		log.error("Exception：", e);
		Result r = new Result(Result.FAIL_CODE, "Internal Exception.");
		return r;
	}

	/**
	 * 用户操作导致的异常，需要给用户提示的
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = BizException.class)
	//@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Result handleParamsInvalidException(BizException e) {
		log.error("Biz exception：{}", e);
		Result r;
		if (StringUtils.isNotEmpty(e.getDesc())) {
			r = new Result(e.getCode(), e.getDesc());
		} else {
			r = new Result(e.getCode(), I18nUtils.getMessage(String.valueOf(e.getCode())));
		}
		return r;
	}

}
